package com.lizhenhua.fmmall.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lizhenhua.fmmall.vo.ResStatus;
import com.lizhenhua.fmmall.vo.ResultVo;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;
//实现拦截器的接口

@Component //交给springboot
public class CheckTokenInterceptor implements HandlerInterceptor {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //如果在请求头里面有参数  前端会先发送一个试探的请求  后端必须给响应才可以执行  如果没有响应 则不会发送请求
        // 检验 并响应
        String method = request.getMethod();

        if("OPTIONS".equals(method)){
            return true;
        }

        String token = request.getHeader("token");
        System.out.println("------------------------------------------------:"+token);
        if (token==null|| token.equals("null")  || token=="") {
            ResultVo resultVo = new ResultVo(ResStatus.LOGIN_FAIL_NOT, "未登录 请先登录", null);
            doResponse(response, resultVo);
        } else {
            try {
                String s = stringRedisTemplate.boundValueOps(token).get();
                if (s == null) {
                    ResultVo resultVo = new ResultVo(ResStatus.LOGIN_FAIL_NOT, "未登录 请先登录", null);
                    doResponse(response, resultVo);
                }else {
                    stringRedisTemplate.boundValueOps(token).expire(20, TimeUnit.SECONDS);
                    return  true;
                }
                /*
                // 用jwt解析token
                JwtParser parser = Jwts.parser();
                // 必须先给他设置你前面设置的格式
                parser.setSigningKey("aaa123");
                // 过期和格式不一样都会爆出 异常 这是校验的代码
                Jws<Claims> claimsJws = parser.parseClaimsJws(token);
*/


            } catch (ExpiredJwtException e) {
                ResultVo resultVo = new ResultVo(ResStatus.LOGIN_FAIL_OVERDUE, "登录过期", null);
                doResponse(response, resultVo);

            } catch (UnsupportedJwtException e){
                ResultVo resultVo = new ResultVo(ResStatus.NO, "token不合法，请自重", null);
                doResponse(response, resultVo);
            }catch (Exception e) {
                ResultVo resultVo = new ResultVo(ResStatus.LOGIN_FAIL_NOT, "请先登录", null);
                doResponse(response, resultVo);
            }

        }
        return false;
    }

    private void doResponse(HttpServletResponse response, ResultVo resultVo) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        String s = new ObjectMapper().writeValueAsString(resultVo);
        out.print(s);
        out.flush();
        out.close();
    }


}
